package com.system.util;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CreateBucketRequest;
import com.system.constant.AliyunConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Local;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

@Slf4j
public class AliyunUtil {


    /**
     * 阿里云上传资源
     * @param file
     * @return
     */
    public static String uploadFile(MultipartFile file) {

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();

            //截取原始文件名的后缀 dfdfdf.png
            String extension = originalFilename.substring(originalFilename.indexOf("."));

            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;

            OSS ossClient = new OSSClientBuilder().build(AliyunConstants.endpoint, AliyunConstants.accessKeyId, AliyunConstants.accessKeySecret);

            // 判断Bucket是否存在
            if (!ossClient.doesBucketExist(AliyunConstants.bucketName)){
                ossClient.createBucket(new CreateBucketRequest(AliyunConstants.bucketName));
            }
            String directory = AliyunConstants.directory + StringUtils.yearAndMonthFolder() + objectName;

            ossClient.putObject(AliyunConstants.bucketName, directory, file.getInputStream());

            ossClient.shutdown();
            log.info(directory," 资源上传阿里云成功！");

            return directory;
        } catch (IOException e) {
            e.printStackTrace();
            return "资源上传错误！";
        }
    }

}
